<template>
  <div class="app-container calendar-list-container">
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :before-close="handleClose" :show-close="false">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="100px"
               style='width: 400px; margin-left:50px;'>
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <!--<el-form-item label="联系方式" prop="type">-->
          <!--<el-input v-model="temp.contact"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="公司地址" prop="address">
          <el-input v-model="temp.address"></el-input>
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="taxIdentificationCode">
          <el-input v-model="temp.taxIdentificationCode"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="pushToLogin" class="el-col-lg-offset-3">返回登录</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确 定</el-button>
        <el-button v-else type="primary" @click="updateData">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getCompany, addCompany, editCompany } from '../../api/company'
  import router from '../../router'
  import store from '../../store'
  import { setLoginUser, getLoginUser } from '../../utils/auth'

  export default {
    name: 'company',
    data() {
      return {
        companyInfo: Object,
        temp: {
          address: '',
          contact: '',
          name: '',
          taxIdentificationCode: ''
        },
        textMap: {
          update: '编辑',
          create: '请添加公司完成注册'
        },
        dialogStatus: '',
        listLoading: false,
        dialogFormVisible: false,
        rules: {
          name: [{ required: true, message: '公司名称必填', trigger: 'blur' }],
          address: [{ required: true, message: '公司地址必填', trigger: 'blur' }],
          contact: [{ required: false, message: '公司联系方式必填', trigger: 'blur' }],
          taxIdentificationCode: [{ required: true, message: '授权码必填', trigger: 'blur' }]
        }
      }
    },
    filters: {},
    created() {
      this.getConpany()
    },
    methods: {
      pushToLogin() {
        this.$store.dispatch('LogOut').then(() => {
          location.reload()// 为了重新实例化vue-router对象 避免bug
        })
      },
      handleClose(done) {
        // do nothing
      },
      getConpany() {
        this.listLoading = true
        getCompany().then((response) => {
          this.companyInfo = response.data
          this.$store.dispatch('Company', this.companyInfo)
          this.listLoading = false
          this.$router.push('/')
        }).catch((error) => {
          this.dialogStatus = 'create'
          this.dialogFormVisible = true
        })
      },
      handleModifyStatus(row, status) {
        editCompany(this.temp).then(() => {
          this.list.unshift(this.temp)
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '创建成功',
            type: 'success',
            duration: 2000
          })
        })
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      resetTemp() {
        this.temp = {
          address: '',
          contact: '',
          name: '',
          taxIdentificationCode: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            addCompany(this.temp).then(() => {
              this.dialogFormVisible = false
              this.companyInfo = this.temp
              this.$store.dispatch('Company', this.companyInfo)
              let data = getLoginUser()
              data.authorities = ['ROLE_ADMIN']
              data.companyId = 1
              setLoginUser(data)
              this.$store.dispatch('ResetRoles', ['ROLE_ADMIN'])
              store.dispatch('GenerateRoutes', {roles: ['ROLE_ADMIN']}).then(() => { // 生成可访问的路由表
                router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
                // next({...to, replace: true}) // hack方法 确保addRoutes已完成 ,replace: true so the navigation will not leave a history record
                this.$router.push('/')
              })
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })

            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            editCompany(tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row) {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      }
    }
  }

</script>
